package com.hxb.example.handler;

import com.hxb.example.handler.annotation.XxlJob;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor, ApplicationContextAware {

    private static final Map<String, Function<String, String>> FUNCTION_MAP = new HashMap<>();
    private ApplicationContext applicationContext;

    @Override
    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        for (Method method : beanType.getDeclaredMethods()) {
            if (method.isAnnotationPresent(XxlJob.class)) {
                XxlJob xxlJob = method.getAnnotation(XxlJob.class);
                if (StringUtils.hasLength(xxlJob.init())) {
                    beanDefinition.setInitMethodName(xxlJob.init());
                }
                if (StringUtils.hasLength(xxlJob.destroy())) {
                    beanDefinition.setDestroyMethodName(xxlJob.destroy());
                }
                if (FUNCTION_MAP.containsKey(xxlJob.value())) {
                    throw new RuntimeException();
                }
                JobHandler.addJob(applicationContext, xxlJob.value(), beanName, method);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
